﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using ONCALL_ENTRY;

public partial class OnCallSchedule : System.Web.UI.Page
{
    #region Connection Constants

    //I've set the DB Connection stuff as global variables...you can change these to work with your page as needed
    string DB_CONNECTION = "Data Source=MICHAEL-PC\\SQLEXPRESS;Initial Catalog=ON-CALL;Integrated Security=True";
    int CLIENT_ID = 1;

    #endregion

    #region Globals

    List<OnCallEntry> ENTRIES;
    Style labelStyle;
    Style noteStyle;
    Style currentLabelStyle;
    Style currentNoteStyle;

    #endregion

    #region Get/Sets for Rows and Columns

    // Columns property to hold the Columns in the ViewState
    protected int Rows
    {
        get { return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0; }
        set { ViewState["Rows"] = value; }
    }

    // Columns property to hold the Columns in the ViewState
    protected int Columns
    {
        get { return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0; }
        set { ViewState["Columns"] = value; }
    }

    #endregion

    #region Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        ENTRIES = new List<OnCallEntry>();

        //Create styles
        labelStyle = new Style();
        labelStyle.Font.Size = FontUnit.Small;
        labelStyle.Font.Name = "Tahoma";

        currentLabelStyle = new Style();
        currentLabelStyle.Font.Size = FontUnit.Small;
        currentLabelStyle.Font.Name = "Tahoma";
        currentLabelStyle.BackColor = System.Drawing.Color.Yellow;

        // Run only once a postback has occured
        CreateDynamicTable();

    }

    #endregion

    #region Get Schedules on Button Click

    public List<OnCallEntry> GetEntries(SqlCommand command)
    {
        List<OnCallEntry> newList = new List<OnCallEntry>();
        SqlConnection conn = new SqlConnection(DB_CONNECTION);
        try
        {
            conn.Open();
        }
        catch (Exception ex) { System.Console.WriteLine("Error connecting to SQL Database: " + ex.ToString()); }
        command.Connection = conn;
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            newList.Add(new OnCallEntry(reader));
        }
        return newList;
    }

    protected void GetToday(object sender, EventArgs e)
    {
        ENTRIES = GetEntries(getSelectDateCommand(CLIENT_ID, new SqlDateTime(DateTime.Today)));
        Rows = ENTRIES.Count;
        Columns = 2;
        CreateDynamicTable();
    }

    protected void GetNext12Hours(object sender, EventArgs e)
    {
        //If current time is PM, get tomorrow's events and todays and combine them
        //to get the events for the next 12 hours
        if (DateTime.Now.TimeOfDay > new TimeSpan(12, 0, 0))
        {
            List<OnCallEntry> tomorrowEntries = new List<OnCallEntry>();
            DateTime tomorrow = DateTime.Today.AddDays(1);
            //Get tomorrow's entries
            tomorrowEntries = GetEntries(getSelectDateCommand(CLIENT_ID, new SqlDateTime(tomorrow)));
            ENTRIES = GetEntries(getSelectDateCommand(CLIENT_ID, new SqlDateTime(DateTime.Today)));

            for (int i = 0; i < ENTRIES.Count; i++)
            {
                if (ENTRIES[i].EndTime < DateTime.Now)
                    ENTRIES.RemoveAt(i);
            }
            DateTime twelveHoursFromNow = DateTime.Now.AddHours(12);
            for (int i = 0; i < tomorrowEntries.Count; i++)
            {
                if (tomorrowEntries[i].StartTime < twelveHoursFromNow)
                    ENTRIES.Add(tomorrowEntries[i]);
            }
        }
        // If current time is AM, just get the events for today and remove the ones that are
        // starting after 12 hours from right now.
        else
        {
            ENTRIES = GetEntries(getSelectDateCommand(CLIENT_ID, new SqlDateTime(DateTime.Today)));
            DateTime twelveHoursFromNow = DateTime.Now.AddHours(12);
            for (int i = 0; i < ENTRIES.Count; i++)
            {
                if (ENTRIES[i].StartTime < twelveHoursFromNow)
                    ENTRIES.RemoveAt(i);
            }
        }
        Rows = ENTRIES.Count;
        Columns = 2;
        CreateDynamicTable();
    }

    public SqlCommand getSelectDateCommand(int client, SqlDateTime today)
    {
        string query = "SELECT * FROM data" + " WHERE (ClientID = @cID AND ((StartDate = @today) OR (StartDate < @today AND EndDate > @today  AND (Daily = 1 OR (Weekly = 1 AND ";
        DateTime dt = (DateTime)today;
        switch (dt.DayOfWeek)
        {
            case DayOfWeek.Monday:
                query += "Mon = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Tuesday:
                query += "Tue = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Wednesday:
                query += "Wed = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Thursday:
                query += "Thu = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Friday:
                query += "Fri = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Saturday:
                query += "Sat = 1))))) ORDER BY StartTime";
                break;
            case DayOfWeek.Sunday:
                query += "Sun = 1))))) ORDER BY StartTime";
                break;
        };
        SqlCommand comm = new SqlCommand(query);
        comm.Parameters.Add(new SqlParameter("@cID", client));
        comm.Parameters.Add(new SqlParameter("@today", today));
        return comm;
    }

    #endregion

    #region Dynamic Table Creation

    private void CreateDynamicTable()
    {
        PlaceHolder1.Controls.Clear();

        int tblRows = Rows;
        int tblCols = Columns;
        Table tbl = new Table();
        PlaceHolder1.Controls.Add(tbl);

        for (int i = 0; i < ENTRIES.Count; i++)
        {
            TableRow tr = new TableRow();

            TableCell tc1 = new TableCell();
            Label label1 = new Label();

            TableCell tc2 = new TableCell();
            Label label2 = new Label();

            bool current = false;

            if (!ENTRIES[i].StartTime.IsNull && !ENTRIES[i].EndTime.IsNull)
            {
                DateTime d1 = (DateTime)ENTRIES[i].StartTime;
                DateTime d2 = (DateTime)ENTRIES[i].EndTime;
                if (d1.TimeOfDay.TotalMinutes < DateTime.Now.TimeOfDay.TotalMinutes &&
                    d2.TimeOfDay.TotalMinutes > DateTime.Now.TimeOfDay.TotalMinutes)
                    current = true;
                label1.Text = String.Format("{0:t}", d1) + "\t\t-\t\t" + String.Format("{0:t}", d2);
            }
            else
                label1.Text = "NULL";

            if (current)
            {
                currentLabelStyle.Width = 150;
                label1.ApplyStyle(currentLabelStyle);
                currentLabelStyle.Width = 300;
                label2.ApplyStyle(currentLabelStyle);
            }
            else
            {
                labelStyle.Width = 150;
                label1.ApplyStyle(labelStyle);
                labelStyle.Width = 300;
                label2.ApplyStyle(labelStyle);
            }

            label2.Text = ENTRIES[i].Note;

            tc1.Controls.Add(label1);
            tr.Cells.Add(tc1);
            tc2.Controls.Add(label2);
            tr.Cells.Add(tc2);

            // Add the TableRow to the Table
            tbl.Rows.Add(tr);
        }
        // This parameter helps determine in the LoadViewState event,
        // whether to recreate the dynamic controls or not
        ViewState["dynamictable"] = true;
    }

    protected override void LoadViewState(object earlierState)
    {
        base.LoadViewState(earlierState);
        if (ViewState["dynamictable"] == null)
            CreateDynamicTable();
    }

    #endregion
}
